// Package quantumcore 实现四维一体量子引擎
// 整合微观阶序、介观均衡、宏观演化、客观周期四个维度
package quantumcore

import (
	"fmt"
	"time"

	"gitee.com/law2025/law-ai/quantum/internal/quantum-core/macro"
	"gitee.com/law2025/law-ai/quantum/internal/quantum-core/meso"
	"gitee.com/law2025/law-ai/quantum/internal/quantum-core/micro"
	"gitee.com/law2025/law-ai/quantum/internal/quantum-core/objective"
)

// EngineStatus 引擎状态
type EngineStatus string

const (
	StatusInitializing EngineStatus = "initializing"
	StatusRunning      EngineStatus = "running"
	StatusPaused       EngineStatus = "paused"
	StatusError        EngineStatus = "error"
	StatusShutdown     EngineStatus = "shutdown"
)

// Result 处理结果
type Result struct {
	Success     bool
	Data        []byte
	Entropy     float64
	Coherence   float64
	Fitness     float64
	CurrentCycle string
	ProcessTime time.Duration
	Message     string
}

// HealthReport 健康报告
type HealthReport struct {
	Timestamp    time.Time
	Status       EngineStatus
	MicroHealth  map[string]interface{}
	MesoHealth   map[string]interface{}
	MacroHealth  map[string]interface{}
	ObjectiveHealth map[string]interface{}
	OverallScore float64
	Warnings     []string
	Recommendations []string
}

// FourDimensionalEngine 四维一体引擎
type FourDimensionalEngine struct {
	// 四个维度的组件
	Micro      *micro.QuantumSequenceEncoder
	Meso       *meso.DynamicBalanceEngine
	Macro      *macro.EvolutionEngine
	Objective  *objective.RhythmSynchronizer

	// 引擎状态
	Status     EngineStatus
	StartTime  time.Time
	LastUpdate time.Time

	// 配置参数
	Config     *EngineConfig
}

// EngineConfig 引擎配置
type EngineConfig struct {
	MicroConfig struct {
		NumQubits          int
		CoherenceThreshold float64
	}
	MesoConfig struct {
		ChaosThreshold float64
		OrderThreshold float64
	}
	MacroConfig struct {
		PopulationSize int
		MutationRate   float64
	}
	ObjectiveConfig struct {
		EarthResonance float64
		SyncEnabled    bool
	}
}

// NewFourDimensionalEngine 创建新的四维引擎
func NewFourDimensionalEngine(config *EngineConfig) *FourDimensionalEngine {
	if config == nil {
		config = DefaultEngineConfig()
	}

	return &FourDimensionalEngine{
		// 初始化四个维度
		Micro:      micro.NewQuantumSequenceEncoder(config.MicroConfig.NumQubits, config.MicroConfig.CoherenceThreshold),
		Meso:       meso.NewDynamicBalanceEngine(config.MesoConfig.ChaosThreshold, config.MesoConfig.OrderThreshold),
		Macro:      macro.NewEvolutionEngine(config.MacroConfig.PopulationSize, config.MacroConfig.MutationRate),
		Objective:  objective.NewRhythmSynchronizer(),

		Status:     StatusInitializing,
		Config:     config,
	}
}

// DefaultEngineConfig 返回默认配置
func DefaultEngineConfig() *EngineConfig {
	config := &EngineConfig{}
	
	config.MicroConfig.NumQubits = 4
	config.MicroConfig.CoherenceThreshold = 0.85

	config.MesoConfig.ChaosThreshold = 0.7
	config.MesoConfig.OrderThreshold = 0.3

	config.MacroConfig.PopulationSize = 20
	config.MacroConfig.MutationRate = 0.01

	config.ObjectiveConfig.EarthResonance = 7.83
	config.ObjectiveConfig.SyncEnabled = true

	return config
}

// QuantumStartup 量子化启动
func (e *FourDimensionalEngine) QuantumStartup() error {
	e.Status = StatusInitializing
	e.StartTime = time.Now()

	// 1. 检查时间节律
	if !e.Objective.CheckRhythmAlignment() {
		currentCycle := e.Objective.GetCurrentCycle()
		if currentCycle == "休息期" {
			return fmt.Errorf("当前处于休息期，不建议启动量子系统")
		}
	}

	// 2. 同步地球共振
	if err := e.Objective.SyncWithEarthResonance(); err != nil {
		fmt.Printf("警告: 地球共振同步异常 - %v\n", err)
		// 不阻止启动，仅警告
	}

	// 3. 初始化宏观演化种群
	paramRanges := map[string][]float64{
		"coherence": {0.0, 1.0},
		"entropy":   {0.0, 1.0},
		"fitness":   {0.0, 1.0},
	}
	
	e.Macro.SetFitnessFunction(func(sys *macro.System) float64 {
		// 综合适应度函数
		coherence := sys.Parameters["coherence"]
		entropy := sys.Parameters["entropy"]
		return coherence * (1.0 - entropy)
	})

	if err := e.Macro.Initialize(paramRanges); err != nil {
		return fmt.Errorf("宏观演化初始化失败: %w", err)
	}

	e.Status = StatusRunning
	e.LastUpdate = time.Now()

	fmt.Println("✓ 四维量子引擎启动成功")
	fmt.Printf("  - 微观阶序: %d量子比特, 相干阈值=%.2f\n", e.Micro.NumQubits, e.Micro.CoherenceThreshold)
	fmt.Printf("  - 介观均衡: 混沌阈值=%.2f, 有序阈值=%.2f\n", e.Meso.ChaosThreshold, e.Meso.OrderThreshold)
	fmt.Printf("  - 宏观演化: 种群=%d, 变异率=%.3f\n", e.Macro.PopulationSize, e.Macro.MutationRate)
	fmt.Printf("  - 客观周期: 当前=%s, 共振=%.2fHz\n", e.Objective.GetCurrentCycle(), e.Objective.EarthResonance)

	return nil
}

// ProcessData 处理数据（整合四个维度）
func (e *FourDimensionalEngine) ProcessData(data []byte) (*Result, error) {
	if e.Status != StatusRunning {
		return nil, fmt.Errorf("引擎未运行，当前状态: %s", e.Status)
	}

	startTime := time.Now()
	result := &Result{
		Success: false,
	}

	// 1. 微观阶序：量子编码
	quantumState, err := e.Micro.EncodeMicroSequence(data)
	if err != nil {
		result.Message = fmt.Sprintf("微观编码失败: %v", err)
		return result, err
	}
	result.Coherence = quantumState.Coherence

	// 2. 介观均衡：动态平衡
	if err := e.Meso.MaintainEquilibrium(quantumState.Amplitudes); err != nil {
		result.Message = fmt.Sprintf("介观平衡失败: %v", err)
		return result, err
	}
	result.Entropy = e.Meso.CalculateSystemEntropy(quantumState.Amplitudes)

	// 3. 宏观演化：演化一代
	snapshot, err := e.Macro.Evolve()
	if err != nil {
		result.Message = fmt.Sprintf("宏观演化失败: %v", err)
		return result, err
	}
	result.Fitness = snapshot.BestFitness

	// 4. 客观周期：记录当前周期
	result.CurrentCycle = e.Objective.GetCurrentCycle()

	// 5. 量子测量得到输出
	outputData, err := e.Micro.MeasureState(quantumState)
	if err != nil {
		result.Message = fmt.Sprintf("量子测量失败: %v", err)
		return result, err
	}

	result.Success = true
	result.Data = outputData
	result.ProcessTime = time.Since(startTime)
	result.Message = "四维处理完成"

	e.LastUpdate = time.Now()
	return result, nil
}

// CheckQuantumHealth 检查量子健康状态
func (e *FourDimensionalEngine) CheckQuantumHealth() *HealthReport {
	report := &HealthReport{
		Timestamp: time.Now(),
		Status:    e.Status,
		Warnings:  make([]string, 0),
		Recommendations: make([]string, 0),
	}

	// 1. 微观健康检查
	report.MicroHealth = map[string]interface{}{
		"num_qubits":           e.Micro.NumQubits,
		"coherence_threshold":  e.Micro.CoherenceThreshold,
	}

	// 2. 介观健康检查
	mesoReport := e.Meso.GetBalanceReport()
	report.MesoHealth = mesoReport
	
	// 检查熵状态
	if entropy, ok := mesoReport["current_entropy"].(float64); ok {
		if entropy > e.Meso.ChaosThreshold {
			report.Warnings = append(report.Warnings, "系统熵过高，处于混沌状态")
			report.Recommendations = append(report.Recommendations, "建议应用量子纠错")
		} else if entropy < e.Meso.OrderThreshold {
			report.Warnings = append(report.Warnings, "系统熵过低，过于有序")
			report.Recommendations = append(report.Recommendations, "建议引入创造性混沌")
		}
	}

	// 3. 宏观健康检查
	macroReport := e.Macro.GetEvolutionReport()
	report.MacroHealth = macroReport

	// 4. 客观健康检查
	objectiveReport := e.Objective.GetRhythmReport()
	report.ObjectiveHealth = objectiveReport

	// 检查节律对齐
	if aligned, ok := objectiveReport["rhythm_aligned"].(bool); ok && !aligned {
		report.Warnings = append(report.Warnings, "当前不在最佳工作周期")
		report.Recommendations = append(report.Recommendations, 
			fmt.Sprintf("建议等待下一个周期: %v", objectiveReport["next_cycle"]))
	}

	// 计算总体健康分数
	report.OverallScore = e.calculateHealthScore(report)

	return report
}

// Shutdown 关闭引擎
func (e *FourDimensionalEngine) Shutdown() error {
	if e.Status == StatusShutdown {
		return fmt.Errorf("引擎已经关闭")
	}

	fmt.Println("正在关闭四维量子引擎...")

	// 保存演化路径
	evolutionPath := e.Macro.TrackEvolutionPath()
	fmt.Printf("  - 保存演化路径: %d代\n", len(evolutionPath))

	// 保存平衡历史
	balanceReport := e.Meso.GetBalanceReport()
	fmt.Printf("  - 保存平衡历史: %v条记录\n", balanceReport["history_size"])

	// 保存任务记录
	tasks := e.Objective.GetScheduledTasks()
	fmt.Printf("  - 保存任务记录: %d个任务\n", len(tasks))

	e.Status = StatusShutdown
	fmt.Println("✓ 四维量子引擎已安全关闭")

	return nil
}

// GetEngineInfo 获取引擎信息
func (e *FourDimensionalEngine) GetEngineInfo() map[string]interface{} {
	uptime := time.Since(e.StartTime)

	return map[string]interface{}{
		"status":      e.Status,
		"uptime":      uptime.String(),
		"start_time":  e.StartTime.Format("2006-01-02 15:04:05"),
		"last_update": e.LastUpdate.Format("2006-01-02 15:04:05"),
		"config":      e.Config,
	}
}

// 内部辅助方法

func (e *FourDimensionalEngine) calculateHealthScore(report *HealthReport) float64 {
	score := 100.0

	// 根据警告数量扣分
	score -= float64(len(report.Warnings)) * 10.0

	// 根据状态扣分
	if e.Status != StatusRunning {
		score -= 30.0
	}

	// 根据介观熵扣分
	if mesoEntropy, ok := report.MesoHealth["current_entropy"].(float64); ok {
		if mesoEntropy > e.Meso.ChaosThreshold || mesoEntropy < e.Meso.OrderThreshold {
			score -= 20.0
		}
	}

	// 确保分数在[0, 100]范围内
	if score < 0 {
		score = 0
	}

	return score
}
